
import cv2 as cv
import numpy as np
filename = r'E:\images\lena.jpg'
img = cv.imread(filename)
#中值滤波
mid = cv.medianBlur(img, 3)
gray = cv.cvtColor(mid, cv.COLOR_BGR2GRAY)
x_grad = cv.Sobel(gray, cv.CV_32F, 1, 0)
y_grad = cv.Sobel(gray, cv.CV_32F, 0, 1)

x_grad = cv.convertScaleAbs(x_grad)
y_grad = cv.convertScaleAbs(y_grad)

dst = cv.add(x_grad, y_grad, dtype=cv.CV_16S)
dst = cv.convertScaleAbs(dst)
cv.imshow("Sobel", dst)

#canny算子
#高斯平滑处理
gaosi = cv.GaussianBlur(img, (9, 9), 0)

#增强锐度
sharpen_op = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=np.float32)
sharpen_image = cv.filter2D(gaosi, cv.CV_32F, sharpen_op)
sharpen_image = cv.convertScaleAbs(sharpen_image)
#取灰度
gaosi = cv.cvtColor(sharpen_image, cv.COLOR_BGR2GRAY)
cannyImg = cv.Canny(gaosi, 50, 100)
cv.imshow("Canny", cannyImg)

cv.waitKey()
cv.destroyAllWindows()




